package m2;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName Consumer
 * @Description:类描述
 * @Author Tedu
 * @Date 2021/6/29 9:49
 * @Version V1.0
 **/
public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();
        //2.创建队列
        c.queueDeclare("task_queue", true, false, false, null);
        DeliverCallback deliverCallback = new DeliverCallback(){



            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String s = new String(message.getBody());
                System.out.println("收到: "+s);
                //模拟处理耗时消息
                //遍历字符串找到'.'字符,每找到一个暂停1秒
                for (int i=0;i<s.length();i++){
                    if(s.charAt(i) == '.'){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                //手动发送回执 回执,是否确认之前收到的所有消息
                c.basicAck(message.getEnvelope().getDeliveryTag(), false);
                //展示要隔多久才会结束消息处理
                System.out.println("---------消息处理结束");
            }
        };
        CancelCallback cancelCallback = new CancelCallback(){

            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };
        //只接受一条,消息处理完之前不抓取下一条
        //手动下有效
        c.basicQos(1);
        //3.从helloworld接收消息
        /*
         * 第二个参数 true:自动确认 自动ACK
         *          false:手动确认 ,处理完需手动发送回执
         */

        c.basicConsume("task_queue", false, deliverCallback, cancelCallback);

    }}
